//
//  YWMaterialRecordTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/9/19.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMaterialRecordTableViewController.h"
#import "YWMaterialListTableViewController.h"
#import "YWMaterialApplyDetailTableViewController.h"
#import "YWMaterialStockOutDetailTableViewController.h"
#import "YWMaterialReturnBackDetailTableViewController.h"
#import "YWMaterialNumbleCertainTableViewController.h"
#import "YWQrcodeManager.h"
#import "YWScanEquipmentNotMatchVC.h"
#import "YWMaterialStockOutWithNoScanTVC.h"

#import "YWMaterialDetailHeadTableViewCell.h"
#import "YWMaterialRecordApplyBillHeadCell.h"
#import "YWMaterialInfoTableViewCell.h"
#import "YWMaterialCirculatiionInfoTableViewCell.h"

#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UIImage+Extension.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "MBProgressHUD.h"

#import "YWMaterialApply.h"
#import "YWMaterialCirculation.h"
#import "YWMaterialApplyDetail.h"
#import "YWMaterialStockOut.h"
#import "YWMaterialStockOutDetail.h"
#import "YWMaterialReturn.h"
#import "YWMaterialReturnDetail.h"
#import "YWMaterialRelation.h"
#import "YWMaterial.h"
#import "YWMaterialManager.h"
#import "YWMaterialStock.h"
#import "YWHandler.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWMaterialRecordTableViewController (){
    BOOL showTopLine;
    BOOL showBottomLine;
}
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, strong) UIButton *receiveButton;
@property (nonatomic, strong) UIButton *cancelApplyButton;
@property (nonatomic, strong) UIButton *returnBackButton;

@property (nonatomic, strong) NSArray * scanStockOut;
@property (nonatomic, strong) NSArray * scanReturnArray;
@property (nonatomic, strong) UIButton * noScanButton;
@property (nonatomic, strong) UIButton * sureReceiveBtn;
@property (nonatomic, strong) UIButton * rejectReceiveBtn;
@property (nonatomic, strong) UIButton * sureReturnBtn;
@property (nonatomic, strong) UIButton * rejectReturnBtn;
@property (nonatomic, strong) UIButton * noScanReturnBtn;

@property (nonatomic, strong) NSMutableArray *matrialBillArray;
@property (nonatomic, strong) NSMutableArray *matrialCirculationArray;
@end

@implementation YWMaterialRecordTableViewController

- (instancetype)init{
    //加上后会使得section的头部有默认的高度
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"物料进度详情";
    [self notification];
    [self initDataSource];
    [self initTableView];
}

- (void)initTableView{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToListView:)];
    [self.tableView registerClass:[YWMaterialDetailHeadTableViewCell class] forCellReuseIdentifier:YWMaterialDetailHeadTableViewCellIdentifier];
    [self.tableView registerClass:[YWMaterialRecordApplyBillHeadCell class] forCellReuseIdentifier:YWMaterialRecordApplyBillHeadCellIdentifier];
    [self.tableView registerClass:[YWMaterialCirculatiionInfoTableViewCell class] forCellReuseIdentifier:YWMaterialCirculatiionInfoTableViewCellIdentifier];
    self.tableView.tableFooterView = self.footView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self setupFootView];
}

- (void)notification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshStockOutData:) name:KPostStockOutCertainAfterRefreshRecordViewNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshReturnData:) name:KPostReturnCertainAfterRefreshNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initDataSource) name:KPostMaterialApplyReplyNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initDataSource) name:KPostMaterialStockOutReplyNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initDataSource) name:KPostMaterialReturnReplyNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initDataSource) name:KPostMaterialNoScanSureNotification object:nil];
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSMutableArray *)matrialBillArray{
    if (!_matrialBillArray) {
        _matrialBillArray = [NSMutableArray array];
        _matrialCirculationArray = [NSMutableArray  array];
        //从数据库查找相关的单
        if (self.apply && self.stockOut == nil && self.returnBack == nil) {
            NSArray * circulationArray = [[YWMaterialManager shareManager] materialCirculationInfoArrayWithMaterialRelationId:self.apply.materialRelationId];
            [_matrialCirculationArray addObjectsFromArray:circulationArray];
            [_matrialBillArray addObject:self.apply];
            YWMaterialRelation * relation = [[YWMaterialManager shareManager] materialRelationWithMaterialApplyId:self.apply.applyId];
            self.stockOut = [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:relation.stockOutId];
            //去掉领用里的申请单
            if (self.stockOut.stockOutStatus != YWMaterialStatusNoReceive || self.stockOut.stockOutStatus != YWMaterialStatusReject) {
                //去掉扫描领用尚未确认的领用单
                if (self.stockOut.stockOutStatus == YWMaterialStatusHaveStockout || self.stockOut.stockOutStatus == YWMaterialStatusHaveReturned) {
                    [_matrialBillArray addObject:self.stockOut];
                }
            }
            
            self.returnBack = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:relation.returnId];
            if (self.returnBack.returnStatus == YWMaterialStatusHaveReturned) {
                [_matrialBillArray addObject:self.returnBack];
            }
        }else if (self.stockOut && self.returnBack == nil){
            NSArray * circulationArray = [[YWMaterialManager shareManager] materialCirculationInfoArrayWithMaterialRelationId:self.stockOut.materialRelationId];
            [_matrialCirculationArray addObjectsFromArray:circulationArray];
            YWMaterialRelation * relation = [[YWMaterialManager shareManager] materialRelationWithMaterialReceipientId:self.stockOut.stockOutId];
            self.apply = [[YWMaterialManager shareManager] materialApplyWithMaterialApplyId:relation.applyId];
            if (self.apply) {
                [_matrialBillArray addObject:self.apply];
            }
            if (self.stockOut.stockOutStatus != YWMaterialStatusNoReceive) {
               [_matrialBillArray addObject:self.stockOut];
            }
            if (self.apply.applyStatus == YWMaterialStatusReject) {
                [_matrialBillArray removeObject:self.stockOut];
            }
            self.returnBack = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:relation.returnId];
            if (self.returnBack.returnStatus == YWMaterialStatusHaveReturned) {
                [_matrialBillArray addObject:self.returnBack];
            }
        }else{
            NSArray * circulationArray = [[YWMaterialManager shareManager] materialCirculationInfoArrayWithMaterialRelationId:self.returnBack.materialRelationId];
            [_matrialCirculationArray addObjectsFromArray:circulationArray];
            YWMaterialRelation * relation = [[YWMaterialManager shareManager] materialRelationWithMaterialReturnId:self.returnBack.returnId];
            self.apply = [[YWMaterialManager shareManager] materialApplyWithMaterialApplyId:relation.applyId];
            if (self.apply) {
                [_matrialBillArray addObject:self.apply];
            }
            
            self.stockOut = [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:relation.stockOutId];
            if (self.stockOut) {
                [_matrialBillArray addObject:self.stockOut];
            }
//            if (self.returnBack.returnStatus == YWMaterialStatusHaveReturned) {
//               [_matrialBillArray addObject:self.returnBack];
//            }
            if (self.returnBack.returnStatus != YWMaterialStatusHaveStockout) {
                [_matrialBillArray addObject:self.returnBack];
            }
        }
        [self setupFootView];
        //拼接流转信息
        //        [_matrialBillArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            if ([obj isKindOfClass:[YWMaterialApplyViewModel class]]) {
//                if (self.apply.status == YWMaterialDataStatusCancel) {
//                    YWMaterialCirculation *circulation = [[YWMaterialCirculation alloc] init];
//                    circulation.person = self.apply.creator;
//                    circulation.time = self.apply.updateTime;
//                    circulation.status = YWMaterialCirculationStatusCancelApply;
//                    [_matrialCirculationArray addObject:circulation];
//                }
//                if (self.apply.applyStatus == YWMaterialStatusReject) {
//                    YWMaterialCirculation *circulation = [[YWMaterialCirculation alloc] init];
//                    circulation.person = self.apply.rejectUser;
//                    circulation.time = self.apply.updateTime;
//                    circulation.status = YWMaterialCirculationStatusRejectApply;
//                    [_matrialCirculationArray addObject:circulation];
//                }
//                YWMaterialCirculation *circulation = [[YWMaterialCirculation alloc] init];
//                circulation.person = self.apply.creator;
//                circulation.time = self.apply.applyTime;
//                circulation.status = YWMaterialCirculationStatusApply;
//                [_matrialCirculationArray addObject:circulation];
//            }else if ([obj isKindOfClass:[YWMaterialStockOut class]] &&   ![obj isKindOfClass:[YWMaterialReturn class]]){
//                YWMaterialCirculation *circulation = [[YWMaterialCirculation alloc] init];
//                circulation.person = self.stockOut.receiver;
//                circulation.status = YWMaterialCirculationStatusStockOut;
//                circulation.time = self.stockOut.stockOutTime;
//                [_matrialCirculationArray addObject:circulation];
//            }else{
//                YWMaterialCirculation *circulation = [[YWMaterialCirculation alloc] init];
//                circulation.person = self.returnBack.returner;
//                circulation.status = YWMaterialCirculationStatusReturned;
//                circulation.time = self.returnBack.returnTime;
//                [_matrialCirculationArray addObject:circulation];
//            }
//        }];
        [self.tableView reloadData];
   }
    return _matrialBillArray;
}

- (void)initDataSource{
    YWWeakSelf(weakSelf);
    if (weakSelf.apply) {
        [[YWMaterialManager shareManager] requestMaterialApplyWithApplyId:weakSelf.apply.applyId Complete:^(YWMaterialApply *materialApply) {
            if (materialApply) {
                YWMaterialApplyViewModel *applyViewModel = [[YWMaterialManager shareManager] materialApplyWithMaterialApplyId:materialApply.applyId];
                if (applyViewModel) {
                    weakSelf.apply = applyViewModel;
                    weakSelf.matrialBillArray = nil;
                    [weakSelf.tableView reloadData];
                }
            }
        }];
    }
    if (weakSelf.stockOut) {
        [[YWMaterialManager shareManager] scanMaterialReceipientQrcodeWithStockOutId:weakSelf.stockOut.stockOutId creatorId:weakSelf.stockOut.creator.uniqueId isScan:NO WithComplete:^(BOOL success) {
            if (success) {
                YWMaterialStockOut * materialStockOut = [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:weakSelf.stockOut.stockOutId];
                if (materialStockOut) {
                    weakSelf.stockOut = materialStockOut;
                    weakSelf.matrialBillArray = nil;
                    [weakSelf.tableView reloadData];
                }
            }
        }];
    }

    if (weakSelf.returnBack) {
        [[YWMaterialManager shareManager] scanMaterialReturnQrcodeWithReturnId:weakSelf.returnBack.returnId creatorId:weakSelf.returnBack.creator.uniqueId isScan:NO WithComplete:^(BOOL success) {
                if (success) {
                    YWMaterialReturn * materialReturn =   [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:weakSelf.returnBack.returnId];
                    if (materialReturn) {
                        weakSelf.returnBack = materialReturn;
                        weakSelf.matrialBillArray = nil;
                        [weakSelf.tableView reloadData];
                    }
                }  
            }];
        }
    //请求评论
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //申请
        if (weakSelf.apply) {
        dispatch_group_enter(group);
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(weakSelf.apply.applyId).stringValue type:YWReplyRelationTypeMaterialApply WithComplete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        }
        //领用
        if (weakSelf.stockOut) {
        dispatch_group_enter(group);
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(weakSelf.stockOut.stockOutId).stringValue type:YWReplyRelationTypeMaterialReceive WithComplete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        }
        //归还
        if (weakSelf.returnBack) {
        dispatch_group_enter(group);
        [[YWReplyManager shareManager] requestReplysWithRelationId:@(weakSelf.returnBack.returnId).stringValue type:YWReplyRelationTypeMaterialReturn WithComplete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        }
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.matrialBillArray = nil;
            [weakSelf.tableView reloadData];
        });
    });

}

- (void)refreshStockOutData:(NSNotification*)info{
    self.stockOut = info.userInfo[@"stockOut"];
    _matrialBillArray = nil;
    [_matrialBillArray addObject:self.stockOut];
    [self setupFootView];
    [self.tableView reloadData];
}

- (void)refreshReturnData:(NSNotification*)info{
    self.returnBack = info.userInfo[@"materialReturn"];
    _matrialBillArray = nil;
    [_matrialBillArray addObject:self.returnBack];
    [self setupFootView];
    [self.tableView reloadData];
}

- (void)setupFootView{
    YWLoginUser * user = [YWLoginTool loginUser];
    if ([self.matrialBillArray containsObject:self.apply] && ![self.matrialBillArray containsObject:self.stockOut] && ![self.matrialBillArray containsObject:self.returnBack]) {
        if (self.apply.applyStatus == YWMaterialStatusNoReceive && self.apply.status == YWMaterialDataStatusNormal) {
            if (user.uniqueId == self.apply.creator.uniqueId){
                [_footView addSubview:self.cancelApplyButton];
            }
            [_footView addSubview:self.receiveButton];
            [_footView addSubview:self.noScanButton];
        }else{
            _cancelApplyButton.hidden = YES;
            _receiveButton.hidden = YES;
            _noScanButton.hidden = YES;
            _returnBackButton.hidden = YES;
            _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH);
            self.tableView.tableFooterView = _footView;
        }
    }else if ([self.matrialBillArray containsObject:self.stockOut] && ![self.matrialBillArray containsObject:self.returnBack]){
        [_sureReceiveBtn removeFromSuperview];
        [_rejectReceiveBtn removeFromSuperview];
        [_cancelApplyButton removeFromSuperview];
        [_receiveButton removeFromSuperview];
        [_noScanButton removeFromSuperview];
        _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH*2 + 15 * 3);
        self.tableView.tableFooterView = _footView;
        if (self.stockOut.stockOutStatus == YWMaterialStatusStockOutWaitCerturn){
            if (user.uniqueId == self.stockOut.receiver.uniqueId) {//确认领用、拒绝
                [_cancelApplyButton removeFromSuperview];
                [_receiveButton removeFromSuperview];
                [_noScanButton removeFromSuperview];
                [_footView addSubview:self.sureReceiveBtn];
                [_footView addSubview:self.rejectReceiveBtn];
            }
        }else{
            _returnBackButton.hidden = NO;
            [_footView addSubview:self.noScanReturnBtn];
            [_footView addSubview:self.returnBackButton];
        }
    }else{
        [_sureReceiveBtn removeFromSuperview];
        [_rejectReceiveBtn removeFromSuperview];
        [_cancelApplyButton removeFromSuperview];
        [_receiveButton removeFromSuperview];
        [_noScanButton removeFromSuperview];
        [_returnBackButton removeFromSuperview];
        [_noScanReturnBtn removeFromSuperview];
        _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH*2 + 15 * 3);
        if (self.returnBack.returnStatus == YWMaterialStatusReturnWaitCerturn) {//确认归还、拒绝
            if (user.uniqueId == self.returnBack.creator.uniqueId) {
                [_footView addSubview:self.sureReturnBtn];
                [_footView addSubview:self.rejectReturnBtn];
            }else{
                [_sureReturnBtn removeFromSuperview];
                [_rejectReturnBtn removeFromSuperview];
            }
        }else{
            [_sureReturnBtn removeFromSuperview];
            [_rejectReturnBtn removeFromSuperview];
            _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH);
            self.tableView.tableFooterView = _footView;
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return section==0? self.matrialBillArray.count : self.matrialCirculationArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        id object = self.matrialBillArray[indexPath.row];
        YWMaterialDetailHeadTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialDetailHeadTableViewCellIdentifier];
        if ([object isKindOfClass:[YWMaterialApplyViewModel class]]) {
            YWMaterialRecordApplyBillHeadCell * applyCell = [tableView dequeueReusableCellWithIdentifier:YWMaterialRecordApplyBillHeadCellIdentifier];
            [self configureApplyHeadViewCell:applyCell atIndexPath:indexPath];
            return applyCell;
        }else if ([object isKindOfClass:[YWMaterialStockOut class]]){
            [self configureStockOutHeadViewCell:cell atIndexPath:indexPath];
            return cell;
        }else if ([object isKindOfClass:[YWMaterialReturn class]]){
            [self configureReturnHeadViewCell:cell atIndexPath:indexPath];
            return cell;
        }else{
            return [[UITableViewCell alloc] init];
        }
    }else{
        YWMaterialCirculatiionInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialCirculatiionInfoTableViewCellIdentifier];
        //        上下线的显示
        cell.isFirstRow = NO;
        if (indexPath.row == 0) {
            showTopLine = NO;
            showBottomLine = YES;
            cell.isFirstRow = YES;
        } else if (indexPath.row == (self.matrialCirculationArray.count - 1)){
            showTopLine = YES;
            showBottomLine = NO;
        } else {
            showTopLine = YES;
            showBottomLine = YES;
        }
        UIView *topLine = (UILabel *)[cell viewWithTag:KTopLineTag];
        UIView *bottomLine = (UILabel *)[cell viewWithTag:KBottomLineTag];
        topLine.hidden = !showTopLine;
        bottomLine.hidden = !showBottomLine;
        [self configureMaterialCirculatiionInfoTableViewCell:cell atIndexPath:indexPath];
        return cell;
    }
    
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section==0) {
//        id object = self.matrialBillArray[indexPath.row];
//    if ([object isKindOfClass:[YWMaterialApplyViewModel class]]) {
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialRecordApplyBillHeadCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialRecordApplyBillHeadCell *cell) {
//                [self configureApplyHeadViewCell:cell atIndexPath:indexPath];
//            }];
//    }else if ([object isKindOfClass:[YWMaterialStockOut class]]){
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialDetailHeadTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialDetailHeadTableViewCell *cell) {
//                [self configureStockOutHeadViewCell:cell atIndexPath:indexPath];
//                }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialDetailHeadTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialDetailHeadTableViewCell *cell) {
//            [self configureReturnHeadViewCell:cell atIndexPath:indexPath];
//        }];
//}
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialCirculatiionInfoTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialCirculatiionInfoTableViewCell *cell) {
//           [self configureMaterialCirculatiionInfoTableViewCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        id object = self.matrialBillArray[indexPath.row];
    if ([object isKindOfClass:[YWMaterialApplyViewModel class]]) {
        YWMaterialApplyDetailTableViewController * applyDetail = [[YWMaterialApplyDetailTableViewController alloc] init];
        applyDetail.apply = self.matrialBillArray[indexPath.row];
        [self.navigationController pushViewController:applyDetail animated:YES];
    }else if ([object isKindOfClass:[YWMaterialStockOut class]]){
        YWMaterialStockOutDetailTableViewController * stockOutDetail = [[YWMaterialStockOutDetailTableViewController alloc] init];
        stockOutDetail.receipient = self.matrialBillArray[indexPath.row];
        [self.navigationController pushViewController:stockOutDetail animated:YES];
    }else{
        YWMaterialReturnBackDetailTableViewController * returnBackDetail = [[YWMaterialReturnBackDetailTableViewController alloc] init];
        returnBackDetail.returnBack = self.matrialBillArray[indexPath.row];
        [self.navigationController pushViewController:returnBackDetail animated:YES];
         }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (void)configureApplyHeadViewCell:(YWMaterialRecordApplyBillHeadCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialApplyViewModel * materialApply = self.matrialBillArray[indexPath.row];
    cell.apply = materialApply;
}

- (void)configureStockOutHeadViewCell:(YWMaterialDetailHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialStockOut * materialStockOut = self.matrialBillArray[indexPath.row];
    cell.receipient = materialStockOut;
}

- (void)configureReturnHeadViewCell:(YWMaterialDetailHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialReturn * materialReturn = self.matrialBillArray[indexPath.row];
    cell.returnBack = materialReturn;
}

- (void)configureMaterialCirculatiionInfoTableViewCell:(YWMaterialCirculatiionInfoTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    YWMaterialCirculation * circulation = self.matrialCirculationArray[indexPath.row];
    cell.circulation = circulation;
}

- (UITableViewCell*)cellWithTable:(UITableView*)tableView{
    static NSString *identifier = @"YWMaterialRecordTableViewControllerIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (UIView *)footView{
    
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        _footView = footView;
    }
    [_footView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH*2 + 15 * 3);
    return _footView;
}

- (UIButton *)receiveButton{
    if (!_receiveButton) {
        UIButton* receiveButton = [UIButton buttonWithType:UIButtonTypeSystem];
        receiveButton.frame = CGRectMake((SCREEN_WIDTH - 10 * 2)/2+10, 15, (SCREEN_WIDTH - 10 * 2)/2, kButtonH);
        [receiveButton setBackgroundColor:[UIColor customBlueColor]];
        [receiveButton setTitle:@"领用" forState:UIControlStateNormal];
        receiveButton.titleLabel.font = kBoldTitleFont;
        [receiveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [receiveButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [receiveButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        receiveButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        receiveButton.clipsToBounds = YES;
        receiveButton.layer.cornerRadius = 5.0;
        [receiveButton addTarget:self action:@selector(handleReceiveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        _receiveButton = receiveButton;
        [_footView addSubview:_receiveButton];
    }
    return _receiveButton;
}

- (UIButton *)noScanButton{
    if (!_noScanButton) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"出库" forState:UIControlStateNormal];
        button.titleLabel.font = kBoldTitleFont;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 5.0;
        button.layer.borderColor = [UIColor customYellowColor].CGColor;
        button.frame = CGRectMake(10, 15,(SCREEN_WIDTH - 10 * 2)/2, kButtonH);
        _noScanButton = button;
        [_footView addSubview:_noScanButton];
    }
    return _noScanButton;
}



- (UIButton *)returnBackButton{
    if (!_returnBackButton) {
        UIButton* returnBackButton = [UIButton buttonWithType:UIButtonTypeSystem];
        returnBackButton.frame = CGRectMake(10, 15+kButtonH+10, SCREEN_WIDTH - 10 * 2, kButtonH);
        [returnBackButton setBackgroundColor:[UIColor customBlueColor]];
        [returnBackButton setTitle:@"归还物料" forState:UIControlStateNormal];
        returnBackButton.titleLabel.font = kBoldTitleFont;
        [returnBackButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [returnBackButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [returnBackButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        returnBackButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        returnBackButton.layer.borderWidth = 1.0;
        returnBackButton.clipsToBounds = YES;
        returnBackButton.layer.cornerRadius = 5.0;
        [returnBackButton addTarget:self action:@selector(handleReturnBackButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        _returnBackButton = returnBackButton;
        [_footView addSubview:_returnBackButton];
    }
    return _returnBackButton;
}

- (UIButton *)noScanReturnBtn{
    if (!_noScanReturnBtn) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"入库" forState:UIControlStateNormal];
        button.titleLabel.font = kBoldTitleFont;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customYellowColor];
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        [button addTarget:self action:@selector(handleNoScanBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 5.0;
        button.layer.borderColor = [UIColor customYellowColor].CGColor;
        button.frame = CGRectMake(10, 15,SCREEN_WIDTH - 10 * 2, kButtonH);
        _noScanReturnBtn = button;
        [_footView addSubview:_noScanReturnBtn];
    }
    return _noScanReturnBtn;
}

- (void)handleReceiveButtonEvent:(UIButton *)sender{
    [[YWQrcodeManager shareManager]clickMaterialScanWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        self.scanStockOut = [qrcodeId componentsSeparatedByString:@","];
       if ([self.scanStockOut containsObject:@"material_stock_out"]) {
           NSInteger applyId = [self.scanStockOut[2] integerValue];
           //二维码Id要与申请单Id一致才匹配
           if (applyId != self.apply.applyId) {
               YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
               senmVC.showContent = @"申请单不匹配!";
               [qrCodeReaderViewController.navigationController pushViewController:senmVC animated:YES];
           }else{
               dispatch_async(dispatch_get_main_queue(), ^{
                   [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                       NSInteger stockOutId = [self.scanStockOut[3] integerValue];
                       [self qrcodeSuccessRequestApplyAndMaterialStockOutWithStockOutId:stockOutId];
                   }];
               });
           }
       }else{
           YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
           senmVC.showContent = @"非物料二维码，请确认!";
           [qrCodeReaderViewController.navigationController pushViewController:senmVC animated:YES];
       }
    }];
}

- (void)handleNoScanBtnEvent:(id)sender{
    YWMaterialStockOutWithNoScanTVC * stockOutNoScanTVC = [[YWMaterialStockOutWithNoScanTVC alloc] init];
    YWMaterialRelation * relation = [[YWMaterialManager shareManager] materialRelationWithMaterialApplyId:self.apply.applyId];
    if (self.stockOut.stockOutStatus == YWMaterialStatusNoReceive) {
        self.stockOut = [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:relation.stockOutId];
        self.stockOut.receiver = self.apply.creator;
        stockOutNoScanTVC.stockOut = self.stockOut;
        stockOutNoScanTVC.isApplySure = YES;
    }else{
        self.returnBack = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:relation.returnId];
        self.returnBack.creator = self.stockOut.creator;
        stockOutNoScanTVC.retrunBack = self.returnBack;
        stockOutNoScanTVC.isApplySure = NO;
    }
    
    [self.navigationController pushViewController:stockOutNoScanTVC animated:YES];
}

- (void)qrcodeSuccessRequestApplyAndMaterialStockOutWithStockOutId:(NSInteger)stockOutId{
    [self.HUD show:YES];
    NSInteger creatorId = self.scanStockOut.count>=2?[self.scanStockOut[1] integerValue] : 0;
    [[YWMaterialManager shareManager] scanMaterialReceipientQrcodeWithStockOutId:stockOutId creatorId:creatorId isScan:YES WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            YWMaterialStockOut * materialStockOut =
            [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:stockOutId];
            //新要求改为跳转页面，跳转时要把self.scanStockOut传过去
            YWMaterialNumbleCertainTableViewController * certainVC = [YWMaterialNumbleCertainTableViewController new];
            certainVC.stockOut = materialStockOut;
            certainVC.scanStockOut = self.scanStockOut;
            [self.navigationController pushViewController:certainVC animated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"请求领用单失败，请重新扫描"];
        }
    }];
}

- (void)handleReturnBackButtonEvent:(UIButton *)sender{
    [[YWQrcodeManager shareManager]clickMaterialScanWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        self.scanReturnArray = [qrcodeId componentsSeparatedByString:@","];
        //二维码Id要与领用单Id一致才匹配
        if ([self.scanReturnArray containsObject:@"material_return"]){
            NSInteger stockOutId = self.scanReturnArray.count>=3? [self.scanReturnArray[2] integerValue]:0;
            if (stockOutId != self.stockOut.stockOutId) {
                YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
                senmVC.showContent = @"领用单不匹配!";
                [qrCodeReaderViewController.navigationController pushViewController:senmVC animated:YES];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                        NSInteger returnId = [self.scanReturnArray[3] integerValue];
                        YWLog(@"returnId = %ld",(long)returnId);
                        [self qrcodeSuccessRequestReturnWithReturnId:returnId];
                    }];
                });
            }
        }else{
            YWScanEquipmentNotMatchVC* senmVC = [[YWScanEquipmentNotMatchVC alloc] init];
            senmVC.showContent = @"非物料二维码，请确认!";
            [qrCodeReaderViewController.navigationController pushViewController:senmVC animated:YES];
        }
    }];
}

- (void)qrcodeSuccessRequestReturnWithReturnId:(NSInteger)returnId
{
    [self.HUD show:YES];
    NSInteger creatorId = [self.scanReturnArray[1] integerValue];
    [[YWMaterialManager shareManager] scanMaterialReturnQrcodeWithReturnId:returnId creatorId:creatorId isScan:YES WithComplete:^(BOOL success) {
        [self.HUD hide:YES];
        if (success) {
            YWMaterialReturn * materialReturn = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:returnId];
            //改为跳转页面，要把self.scanReturnArray传过去
            YWMaterialNumbleCertainTableViewController * certainVC = [YWMaterialNumbleCertainTableViewController new];
            certainVC.returnBack = materialReturn;
            certainVC.scanReturn = self.scanReturnArray;
            [self.navigationController pushViewController:certainVC animated:YES];
        }else{
            [YWCommonTool showTextHUDWithContent:@"请求归还单失败，请重新扫描"];
        }
    }];
}

- (UIButton *)sureReceiveBtn{
    if (!_sureReceiveBtn) {
        UIButton* sureReceiveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        sureReceiveBtn.frame = CGRectMake(10, 15, SCREEN_WIDTH - 10*2, kButtonH);
        [sureReceiveBtn setBackgroundColor:[UIColor customBlueColor]];
        [sureReceiveBtn setTitle:@"确认领用" forState:UIControlStateNormal];
        sureReceiveBtn.titleLabel.font = kBoldTitleFont;
        [sureReceiveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureReceiveBtn setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [sureReceiveBtn setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        sureReceiveBtn.layer.borderColor = [UIColor customBlueColor].CGColor;
        sureReceiveBtn.clipsToBounds = YES;
        sureReceiveBtn.layer.cornerRadius = 5.0;
        [sureReceiveBtn addTarget:self action:@selector(handleSureReceiveBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _sureReceiveBtn = sureReceiveBtn;
        [_footView addSubview:_sureReceiveBtn];
    }
    return _sureReceiveBtn;
}

- (UIButton *)rejectReceiveBtn{
    if (!_rejectReceiveBtn) {
        UIButton* rejectReceiveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        rejectReceiveBtn.frame = CGRectMake(10, 30 + kButtonH, SCREEN_WIDTH - 10*2, kButtonH);
        [rejectReceiveBtn setBackgroundColor:[UIColor whiteColor]];
        [rejectReceiveBtn setTitle:@"拒绝" forState:UIControlStateNormal];//拒绝领用
        rejectReceiveBtn.titleLabel.font = kBoldTitleFont;
        [rejectReceiveBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [rejectReceiveBtn setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [rejectReceiveBtn setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        rejectReceiveBtn.layer.borderColor = [UIColor customBlueColor].CGColor;
        rejectReceiveBtn.clipsToBounds = YES;
        rejectReceiveBtn.layer.cornerRadius = 5.0;
        [rejectReceiveBtn addTarget:self action:@selector(handleRejectReceiveBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _rejectReceiveBtn = rejectReceiveBtn;
        [_footView addSubview:_rejectReceiveBtn];
    }
    return _rejectReceiveBtn;
}

- (UIButton *)sureReturnBtn{
    if (!_sureReturnBtn) {
        UIButton* sureReturnBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        sureReturnBtn.frame = CGRectMake(10, 15, SCREEN_WIDTH - 10*2, kButtonH);
        [sureReturnBtn setBackgroundColor:[UIColor customBlueColor]];
        [sureReturnBtn setTitle:@"确认归还" forState:UIControlStateNormal];
        sureReturnBtn.titleLabel.font = kBoldTitleFont;
        [sureReturnBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [sureReturnBtn setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [sureReturnBtn setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        sureReturnBtn.layer.borderColor = [UIColor customBlueColor].CGColor;
        sureReturnBtn.clipsToBounds = YES;
        sureReturnBtn.layer.cornerRadius = 5.0;
        [sureReturnBtn addTarget:self action:@selector(handleSureReturnBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _sureReturnBtn = sureReturnBtn;
        [_footView addSubview:_sureReturnBtn];
    }
    return _sureReturnBtn;
}

- (UIButton *)rejectReturnBtn{
    if (!_rejectReturnBtn) {
        UIButton* rejectReturnBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        rejectReturnBtn.frame = CGRectMake(10, 30 + kButtonH, SCREEN_WIDTH - 10*2, kButtonH);
        [rejectReturnBtn setBackgroundColor:[UIColor whiteColor]];
        [rejectReturnBtn setTitle:@"拒绝" forState:UIControlStateNormal];//拒绝归还
        rejectReturnBtn.titleLabel.font = kBoldTitleFont;
        [rejectReturnBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [rejectReturnBtn setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [rejectReturnBtn setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        rejectReturnBtn.layer.borderColor = [UIColor customBlueColor].CGColor;
        rejectReturnBtn.clipsToBounds = YES;
        rejectReturnBtn.layer.cornerRadius = 5.0;
        [rejectReturnBtn addTarget:self action:@selector(handleRejectReturnBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _rejectReturnBtn = rejectReturnBtn;
        [_footView addSubview:_rejectReturnBtn];
    }
    return _rejectReturnBtn;
}

- (UIButton *)cancelApplyButton{
    if (!_cancelApplyButton) {
        UIButton* cancelApplyButton = [UIButton buttonWithType:UIButtonTypeSystem];
        cancelApplyButton.frame = CGRectMake(10, 30 + kButtonH, SCREEN_WIDTH - 10*2, kButtonH);
        [cancelApplyButton setBackgroundColor:[UIColor whiteColor]];
        [cancelApplyButton setTitle:@"撤回申请" forState:UIControlStateNormal];
        cancelApplyButton.titleLabel.font = kBoldTitleFont;
        [cancelApplyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelApplyButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [cancelApplyButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        cancelApplyButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        cancelApplyButton.clipsToBounds = YES;
        cancelApplyButton.layer.cornerRadius = 5.0;
        [cancelApplyButton addTarget:self action:@selector(handleCancelApplyButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        _cancelApplyButton = cancelApplyButton;
        [_footView addSubview:_cancelApplyButton];
    }
    return _cancelApplyButton;
}

- (void)handleCancelApplyButtonEvent:(UIButton *)sender{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"撤回申请" message:@"您确定撤回申请吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        YWLoginUser * user = [YWLoginTool loginUser];
        if (user.uniqueId == self.apply.creator.uniqueId) {
            [[YWMaterialManager shareManager] materialApplyDeleteWithApplyId:self.apply.applyId WithComplete:^(NSInteger stateCode) {
                if (stateCode == 200) {
                    [YWCommonTool showTextHUDWithContent:@"撤回成功"];
                    self.apply.status = YWMaterialDataStatusCancel;
                    [[YWMaterialManager shareManager] updateMaterialStatus:YWMaterialDataStatusCancel withApplyId:self.apply.applyId];
                    //撤回后重新刷新数据，改变布局
                    _matrialBillArray = nil;
                    self.apply.updateTime = [[NSDate date] timeIntervalSince1970]*1000;
                    [self setupFootView];
                    [self.tableView reloadData];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostCancelApplyNotification object:nil];
                    //                [self.navigationController popViewControllerAnimated:YES];
                    
                    
                }else if (stateCode == 406){
                    [YWCommonTool showTextHUDWithContent:@"已领用，无法撤回 "];
                }else{
                    [YWCommonTool showTextHUDWithContent:@"没有撤回权限"];
                }
            }];
        }else{
            [YWCommonTool showTextHUDWithContent:@"没有撤回权限"];
        }
    
    }]];
}
#pragma mark- buttonEvent 确认领用、拒绝、确认归还、拒绝等
- (void)handleSureReceiveBtnEvent:(id)sender{
    //确认领用
    [[YWMaterialManager shareManager] postMaterialStockOutReceiveCerturnWithStockOutId:self.stockOut.stockOutId WithComplete:^(BOOL success) {
        if (success) {
           [self initDataSource];
        }
    }];
}

- (void)handleRejectReceiveBtnEvent:(id)sender{
    //拒绝领用
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"拒绝领用备注" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"拒绝领用的原因或备注";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        NSString *rejectReason = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (rejectReason.length>100) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        }else if ([YWCommonTool isContainsEmoji:rejectReason]) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        }else{
            [[YWMaterialManager shareManager] postMaterialStockOutRejectWithStockOutId:self.stockOut.stockOutId note:rejectReason WithComplete:^(BOOL success) {
                if (success) {
                    [self initDataSource];
                }
            }];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)handleSureReturnBtnEvent:(id)sender{
    //确认归还
    [[YWMaterialManager shareManager] postMaterialReturnBackCerturnWithReturnId:self.returnBack.returnId WithComplete:^(BOOL success) {
        if (success) {
            [self initDataSource];
        }
    }];
}

- (void)handleRejectReturnBtnEvent:(id)sender{
    //拒绝归还
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"拒绝归还备注" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.placeholder = @"拒绝归还的原因或备注";
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
        NSString *rejectReason = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if (rejectReason.length>100) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        }else if ([YWCommonTool isContainsEmoji:rejectReason]) {
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        }else{
            [[YWMaterialManager shareManager] postMaterialReturnBackRejectWithReturnId:self.returnBack.returnId note:rejectReason WithComplete:^(BOOL success) {
                if (success) {
                    [self initDataSource];
                }
            }];
        }
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)backToListView:(id)sender{
    UIViewController *vc = nil;
    //返回时，遍历viewController,如果找到该栈的viewcontroller，返回，否则返回上个界面
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[YWMaterialListTableViewController class]]) {
            vc = temp;
            break;
        }
    }
    if (vc) {
        [self.navigationController popToViewController:vc animated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


@end
